package com.xiaokai.model;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;

public class SignatureUtils {

    /**
     * 生成签名
     * @param appSecret 应用密钥
     * @param params 参数Map
     * @return 生成的签名
     */
    public static String generateSignature(String appSecret, TreeMap<String, String> params) {
        StringBuilder sb = new StringBuilder(appSecret);
        params.forEach((k, v) -> {
            if (v != null && !v.isEmpty()) {
                sb.append(k).append(v);
            }
        });
        try {
            String sign = DigestUtils.md5DigestAsHex(sb.toString().getBytes(StandardCharsets.UTF_8));
            return sign.toString().toUpperCase();
        } catch (Exception e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }




    /**
     * 将JSON字符串反序列化为Java对象
     * @param json JSON字符串
     * @return 反序列化的对象
     */
    public static Map<String, Object> deserializeJson(String json) {
        try {
            return new ObjectMapper().readValue(json, Map.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("反序列化JSON字符串失败", e);
        }
    }


    /**
     * 验证签名
     * @param params 签名数据
     * @return 验证结果
     */
    public static boolean verifySignature(String appSecret, String sign,TreeMap params) {
        String signature = generateSignature(appSecret,params);
        // 比对签名
        return signature.equals(sign);
    }

}